package com.fr.lintcode;

import org.junit.Test;

public class Q968 {
    /**
     * @param currency:
     *            a string represents a valid or invalid currency amount
     * @return: return whether the given string is a valid currency
     */
    public boolean validCurrencyAmount(String currency) {
        // write your code here
        if (currency.startsWith("-")) {
            currency = currency.substring(1);
        }
        if (currency.startsWith("(")) {
            if (currency.endsWith(")")) {
                currency = currency.substring(1, currency.length() - 1);
            }
        }

        if (currency.startsWith("D") || currency.startsWith("E") || currency.startsWith("Y")) {

            String[] split = currency.split("\\.");
            boolean fen = false;
            if (split.length > 2) {
                return false;
            } else if (split.length == 2) {
                if (currency.startsWith("Y") || split[1].length() != 2 || !isNumber(split[1])) {
                    return false;
                }
                fen = true;
                currency = split[0];
            }
            currency = currency.substring(1);
            split = currency.split(",");
            if (split.length == 1) {
                if (isNumber(currency)) {
                    if (currency.startsWith("00")) {
                        return false;
                    } else if (currency.startsWith("0")) {
                        return fen || currency.length() == 1;
                    }
                } else {
                    return false;
                }
            } else {
                boolean first = true;
                for (String s : split) {
                    if (!isNumber(s)) {
                        return false;
                    }
                    if (first) {
                        first = false;
                        if (s.startsWith("0")) {
                            return false;
                        }
                        if (s.length() >= 3) {
                            return false;
                        }
                    } else {
                        if (s.length() != 3) {
                            return false;
                        }
                    }
                }
            }

        } else {
            return false;
        }
        return true;
    }

    private boolean isNumber(String s) {
        for (char c : s.toCharArray()) {
            if ('0' > c || '9' < c) {
                return false;
            }
        }
        return true;
    }

    @Test
    public void testA() {
        String s = "Y0.11";
        System.out.println(validCurrencyAmount(s));
    }

}
